package com.dmy.ui;

import com.dmy.config.GameConfig;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.lang.reflect.InvocationTargetException;
import java.util.Random;

public class MainWindow extends JFrame {

    private Tank myTank;
    private JFrame frame ;
    private JPanel panel = new MyJPanel();


    public MainWindow(){
        initComponent();
        frame = this;

        initTanks();
        new Timer(1000, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                frame.setTitle(String.format("x:%s,y:%s,敌军数量:%s,击杀:%s",myTank.getX(),myTank.getY(),((MyJPanel) panel).getEnyTankNum(),((MyTank)myTank).getAttackNum()));
            }
        }).start();
    }

    private void initTanks() {
        myTank = new MyTank(GameConfig.DEFAULT_MYTANK_X, GameConfig.DEFAULT_MYTANK_Y);
        ((MyJPanel)panel).addMyTank(myTank);
        for (int i = 0;i<new Random().nextInt(8)+3;i++){
            ((MyJPanel)panel).addEnyTank(new EnemyTank(panel));
        }
    }

    private void initComponent() {
        this.setTitle("随便写");
        this.setVisible(true);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setResizable(false);
        this.setBounds(200,100, GameConfig.WINDOW_WIDTH,GameConfig.WINDOW_HEIGHT+80);

        // 监听键盘按下事件
        this.addKeyListener(new KeyAdapter() {

            @Override
            public void keyPressed(KeyEvent e) {

                switch (e.getKeyCode()){
                    case 70:
                        ((MyTank)myTank).addLife();
                        break;
                    case 61:
                        ((MyJPanel)panel).addEnyTank(new EnemyTank(panel));
                        break;
                    case 38:
                    case 87:
                        myTank.moveUp(panel);
                        break;
                    case 83:
                    case 40:
                        myTank.moveDown(panel);
                        break;
                    case 65:
                    case 37:
                        myTank.moveLeft(panel);
                        break;
                    case 39:
                    case 68:
                        myTank.moveRight(panel);
                        break;
                    case 32:
                        myTank.attack(panel);
                        break;
                    default:
                }

            }
        });
        this.add(panel);
    }


    public static void main(String[] args) throws InvocationTargetException, InterruptedException {
        EventQueue.invokeAndWait(()->{
            new MainWindow();
        });
    }
}
